package com.telnetnz.ticketdesk.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.ehcache.Element;

import org.apache.log4j.Logger;

import com.rockbb.common.simpleframe.config.SimpleConfig;
import com.rockbb.common.simpleframe.result.ActionResult;
import com.rockbb.common.utilities.i18n.MessageResource;
import com.rockbb.common.utilities.i18n.MessageResourceFactory;
import com.telnetnz.ticketdesk.bean.ProjectToUser;
import com.telnetnz.ticketdesk.bean.Template;
import com.telnetnz.ticketdesk.bean.Ticket;
import com.telnetnz.ticketdesk.bean.TicketComment;
import com.telnetnz.ticketdesk.common.GenericPageMaker;
import com.telnetnz.ticketdesk.common.config.SpringContext;
import com.telnetnz.ticketdesk.dao.entity.TicketCommentEntity;
import com.telnetnz.ticketdesk.dao.wrapper.TicketCommentWrap;

public class TicketCommentService
{
	public static final String[] ORDER_BY = TicketCommentWrap.ORDER_BY;
	public static final int ORDERBY_CREATETIME = 0;
	public static final int ORDERBY_UPDATETIME = 1;
	public static final int ORDERBY_CREATORID = 2;

	public static final String[] ORDER = TicketCommentWrap.ORDER;

	private static Logger logger = Logger.getLogger(TicketCommentService.class);
	private static String CACHE_KEY = "id_";

	public static void sendNotification(TicketComment comment, int language)
	{
		Set<String> recipients = new HashSet<String>();
		recipients.add(comment.getTicket().getCreator().getEmail());
		if (comment.getTicket().getOwner() == null)
		{
			List<ProjectToUser> users = comment.getTicket().getProject().getProjectUsers();
			for (ProjectToUser user: users)
				recipients.add(user.getUser().getEmail());
		}
		else
			recipients.add(comment.getTicket().getOwner().getEmail());

		Map<String, Object> root = new HashMap<String, Object>();
		MessageResource langRes = MessageResourceFactory.getMessageResource(language);

		root.put("comment", comment);
		root.put(ActionResult.MAP_KEY_I18N, langRes.getResourceBundle());	// L("") = i18n method
		root.put(ActionResult.MAP_KEY_CONFIGS, SimpleConfig.getConfigs());	// sf_configs = Global configurations

		Template template = TemplateService.getTemplate(2);
		StringBuffer sb = new StringBuffer()
				.append('[').append(comment.getTicket().getProject().getName()).append("][")
				.append(TicketService.PRIORITIES[comment.getTicket().getPriority()]).append("][")
				.append(TicketService.STATUSES[comment.getTicket().getStatus()]).append("] ")
				.append(comment.getTicket().getSubject()).append(": ")
				.append(langRes.get("comment.new-comment"));
		String subject = sb.toString();

		String formattedContent = GenericPageMaker.process(template.getName(), SimpleConfig.getConfig("encoding"), root);

		SMTPService.sendMail(
				subject, 
				formattedContent, 
				SimpleConfig.getConfig("encoding"),
				recipients);
	}

	/**
	 * Important: This is only for comparison with the updated bean
	 * 
	 * @param id
	 * @return
	 */
	public static TicketComment getRawTicketComment(long id)
	{
		TicketCommentEntity entity = getWrap().select(id);
		return TicketComment.adapt(entity);
	}

	/**
	 * Important: This is the only entry to get the ticket bean, including the methods that return instances list
	 * 
	 * @param uid
	 * @return
	 */
	public static TicketComment getTicketComment(long id)
	{
		Element elm = getWrap().getCache().get(CACHE_KEY + id);
		TicketComment bean;
		if (elm == null)
		{
			TicketCommentEntity entity = getWrap().select(id);
			bean = TicketComment.adapt(entity);
			getWrap().getCache().put(new Element(CACHE_KEY + id, bean));
		}
		else
		{
			bean = (TicketComment) elm.getValue();
		}
		return bean;
	}

	public static void add(TicketComment comment)
	{
		if (comment == null)
			return;
		getWrap().insert(comment.toEntity());
		getWrap().getCache().remove(CACHE_KEY + comment.getId());
	}

	public static void update(TicketComment comment)
	{
		if (comment == null)
			return;
		comment.setUpdateTime(new Date());
		getWrap().update(comment.toEntity());
		getWrap().getCache().remove(CACHE_KEY + comment.getId());
	}

	public static void delete(TicketComment comment)
	{
		if (comment == null)
			return;
		getWrap().delete(comment.toEntity());
		getWrap().getCache().remove(CACHE_KEY + comment.getId());
	}

	public static List<TicketComment> getByPageAndCondition(
			int start,
			int limit, 
			int orderby, 
			int order,
			long ticketId,
			long creatorId,
			long updaterId)
	{
		List<Long> ids = getWrap().selectByPageAndCondition(
				start, limit, orderby, order, ticketId, creatorId, updaterId);
		return adaptIdsList(ids);
	}

	public static long countByCondition(
			long ticketId,
			long creatorId,
			long updaterId)
	{
		return getWrap().countByCondition(ticketId, creatorId, updaterId);
	}

	private static List<TicketComment> adaptIdsList(List<Long> ids)
	{
		List<TicketComment> comments = new ArrayList<TicketComment>();
		if (ids != null && ids.size() > 0)
		{
			for (Long id : ids)
			{
				TicketComment comment = getTicketComment(id);
				if (comment != null)
					comments.add(comment);
			}
		}
		return comments;
	}

	private static TicketCommentWrap getWrap()
	{
		return SpringContext.getTicketCommentWrap();
	}

	public static void main(String[] args)
	{
		
	}
}
